﻿using System;
using System.Linq;
using Loki;
using Luna.Model.Accounting;

namespace Luna.UI.Accounting
{
    public class AccountingLevelGraphViewModel : AccountingGraph
    {
        private LokiCollection<GraphPoint<DateTime, decimal>> _SourcePoints;

        public override object DataSource
        {
            get { return _SourcePoints; }
        }

        public AccountingLevelGraphViewModel()
        {
            _SourcePoints = new LokiCollection<GraphPoint<DateTime, decimal>>();
        }

        protected override void ReloadGraph(object P_Sender, EventArgs e)
        {
            if (AccountID.HasValue)
            {
                IAccount L_Account = ApplicationModel.Accounting.Accounts[AccountID.Value];
                _SourcePoints.Clear();

                // first point
                decimal L_InitialAmount = 0;
                DateTime L_StartDate = L_Account.StartDate > StartDate ? L_Account.StartDate : StartDate;
                if (L_StartDate == L_Account.StartDate)
                {
                    L_InitialAmount = L_Account.InitialAmount;
                }
                else
                {
                    L_InitialAmount = L_Account.InitialAmount + L_Account.Operations.Where(x => x.ExecutionDate <= L_StartDate).Sum(x => x.Amount);
                }

                _SourcePoints.Add(new GraphPoint<DateTime, decimal>() { Argument = L_StartDate, Value = L_InitialAmount });

                // other points
                foreach (var L_OperationGroup in L_Account.Operations.Where(x => x.ExecutionDate > L_StartDate && x.ExecutionDate <= EndDate).OrderBy(x => x.ExecutionDate).GroupBy(x => x.ExecutionDate))
                {
                    L_InitialAmount += L_OperationGroup.Sum(x => x.Amount);
                    _SourcePoints.Add(new GraphPoint<DateTime, decimal>() { Argument = L_OperationGroup.Key, Value = L_InitialAmount });
                }
            }
        }
    }
}
